# -*- coding = utf-8 -*-
# @Time : 2024/6/9 17:50
# @Author : 0505200213石浪
# @File : movies.py
# @Software : PyCharm


from flask import request, render_template, jsonify
from . import bp
import utils
from db_operations import Database

db = Database()


# 电影列表页面
@bp.route('/movie_1/<username>')
def movie_1(username):
    utils.get_movies()
    movie_data = utils.moviesData
    return movie_list(username, movie_data)


# 电影分页逻辑
def movie_list(username, movies):
    page = request.args.get('page', 1, type=int)
    movieTop10 = utils.moviesData[0:10]
    per_page = 20
    total_pages = len(movies) // per_page + (len(movies) % per_page != 0)
    start = (page - 1) * per_page
    end = start + per_page
    movies_on_page = movies[start:end]
    print(len(utils.moviesData))
    return render_template('movie_1.html', movieTop10=movieTop10, movies=movies_on_page, page=page,
                           total_pages=total_pages, username=username)


# 电影搜索
@bp.route('/search/<username>', methods=['GET'])
def search(username):
    country = request.args.get('country')
    year = request.args.get('year')
    query = "SELECT * FROM movieFriends.movies WHERE ink like %s"
    params = [f'%{country}%']
    if '-' in year:
        start_year, end_year = map(int, year.split('-'))
        year_conditions = []
        for y in range(start_year, end_year + 1):
            year_conditions.append("ink LIKE %s")
            params.append(f'%{y}%')
        query += " AND (" + " OR ".join(year_conditions) + ")"
    else:
        query += " AND ink LIKE %s"
        params.append(f'%{year}%')
    movie_search = db.execute(query, params)
    return movie_list(username, movie_search)


# 电影详情
@bp.route('/movie_detail/<username>/<int:movieId>')
def movie_detail(username, movieId):
    target_movie_id = movieId
    movie_details, ranking = None, -1
    utils.get_movies()
    for index, movie_tuple in enumerate(utils.moviesData):
        if movie_tuple[0] == target_movie_id:
            movie_details = utils.moviesData[index]
            utils.get_comments(movieId)
            ranking = index + 1
            break
    if movie_details is None:
        return jsonify({"message": "Movie not found"}), 404
    print(username)
    return render_template('movie_detail.html', movie_details=movie_details, comments=utils.comments,
                           currentUser=username, ranking=ranking)
